package cn.com.dnt.jmxmonitor.server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.dnt.jmxmonitor.util.JSONUtil;

public class JMXSocket {

	 public static final String IP_ADDR = "localhost";//服务器地址   
	public static final int PORT = 8111;//服务器端口号    
	      
	    public static void main(String[] args) {    
	        System.out.println("客户端启动...");    
	        System.out.println("当接收到服务器端字符为 \"OK\" 的时候, 客户端将终止\n");   
	        while (true) {
	        	try {
					Thread.sleep(50);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
	            Socket socket = null;  
	            try {  
	                //创建一个流套接字并将其连接到指定主机上的指定端口号  
	                socket = new Socket(IP_ADDR, PORT);    
	                    
	                //读取服务器端数据    
	                DataInputStream input = new DataInputStream(socket.getInputStream());    
	                //向服务器端发送数据    
	                DataOutputStream out = new DataOutputStream(socket.getOutputStream());    
	                System.out.print("正在发送: \t");    
	                List<Map<String, Object>> list = new ArrayList<>();
	                for (int i = 0; i < 10; i++) {
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("host", "localhost");
						map.put("port", 8999);
						list.add(map);
					}
	                
	                String str = JSONUtil.obj2json(list);
	                System.out.println(str);
	                out.writeUTF(str);    
	                String ret = input.readUTF(); 
	                System.out.println("服务器端返回过来的是: " + ret);    
	                // 如接收到 "OK" 则断开连接    
	                if ("OK".equals(ret)) {    
	                    System.out.println("客户端将关闭连接");    
	                    Thread.sleep(500);    
	                    break;    
	                }    
	                out.close();  
	                input.close();  
	            } catch (Exception e) {  
	                System.out.println("客户端异常:" + e.getMessage());   
	            } finally {  
	                if (socket != null) {  
	                    try {  
	                        socket.close();  
	                    } catch (IOException e) {  
	                        socket = null;   
	                        System.out.println("客户端 finally 异常:" + e.getMessage());   
	                    }  
	                }  
	            }  
	        }    
	    }    
}
